package com.bd.scm.module.qywx.service;

/**
 * Oauth2 Servlet类
 * @author Engineer.Jsp
 * @date 2014.10.13
 */

import com.bd.scm.module.qywx.thread.TokenThread;
import com.bd.scm.module.utils.qywx.GOauth2Core;
import com.bd.scm.module.utils.qywx.WeiXinParamesUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class OAuth2Servlet extends HttpServlet {
     /**
	 *
	 */
	private static final long serialVersionUID = 4440739483644821980L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("UTF-8");
          response.setHeader("Content-type", "text/html;charset=UTF-8");
          response.setCharacterEncoding("UTF-8");
          PrintWriter out = response.getWriter();
          String UserID = null;
          Map<String, String[]> parameterMap = request.getParameterMap();
          Set<Entry<String,String[]>> entrySet = parameterMap.entrySet();
          System.out.println("开始");
          for (Entry<String, String[]> entry : entrySet) {
			System.out.println(entry.getKey()+":"+entry.getValue().toString());
		}
          System.out.println("结束");
          String code = request.getParameter("code");
          if (!"authdeny".equals(code)) {
          String access_token = TokenThread.accessToken.getToken();
          // agentid 跳转链接时所在的企业应用ID 管理员须拥有agent的使用权限；agentid必须和跳转链接时所在的企业应用ID相同
          try {
			    UserID = GOauth2Core.GetUserID(access_token, code, WeiXinParamesUtil.getProperty("agentId"));
          } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
          }
          //request.setAttribute("UserID", UserID);
          }
          else{
              out.print("授权获取失败，至于为什么，自己找原因。。。");
          }
          // 跳转到index.jsp
          out.print("授权获取成功" + UserID);
        }

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
}
